package com.sky.service.impl;

import com.sky.constant.DefaultAddressConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sky.mapper.AddressBookMapper;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    // 注入mapper
    @Autowired
    private AddressBookMapper addressBookMapper;

    /*根据条件查询当前用户所有地址*/
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        List<AddressBook> addressBookList = addressBookMapper.list(addressBook);
        return addressBookList;
    }

    /*用户新增地址方法*/
    @Override
    public void save(AddressBook addressBook) {
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        // 设置地址的userid
        addressBook.setUserId(userId);
        // 设置非默认地址
        addressBook.setIsDefault(0);
        // 调用mapper层插入方法
        addressBookMapper.insert(addressBook);
    }

    /*根据id查询地址信息方法*/
    @Override
    public AddressBook getAddressBookById(Long id) {
        // 调用mapper接口层查询方法
        AddressBook addressBook = addressBookMapper.getAddressBookById(id);
        return addressBook;
    }

    /*根据id修改地址信息*/
    @Override
    public void update(AddressBook addressBook) {
        // 调用mapper层修改方法
        addressBookMapper.update(addressBook);
    }

    /*设置默认地址方法*/
    @Override
    public void setDefault(AddressBook addressBook) {
        // 1.将所有地址都设置成非默认地址,根据用户id修改改用户的所有地址信息
        addressBook.setIsDefault(DefaultAddressConstant.NO_DEFAULT);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultAddressByUserId(addressBook);
        // 2.调用mapper层将当前传递过来的参数"addressBook"设置为默认地址的方法
        addressBook.setIsDefault(DefaultAddressConstant.DEFAULT);
        addressBookMapper.update(addressBook); // 调用update方法, 设置当前地址为默认地址, 因为addressBook中包含了id,所以可以直接修改
    }

    /*根据id删除地址*/
    @Override
    public void deleteById(Long id) {
        // 直接调用mapper层删除方法
        addressBookMapper.deleteById(id);
    }
}
